<template>
	<!-- components/bottom_nav/bottom_nav.wxml -->
	<view>
		<view :class="'bottomBox ' + grayscale" v-if="bottomNavArr.length">
			<view :class="'li ficon ' + (item.fabu ? 'fabu' : '')"
				:data-module="module"
				:data-url="activeIndex!=index?platForm=='web'?item.url:item.miniPath||item.url:''"
				@tap="goLink($event,Boolean(item.fabu)||item.url.includes('currentPageOpen'))" 
				:data-type="1" v-for="(item, index) in bottomNavArr" :key="index">
				<image :src="activeIndex == index || (activeIndex == 'message' && item.message) ? item.icon_h : item.icon"
					class="image"></image>

				<view class="msg" v-if="item.message && (msgNum != 0||total!=0)&&total!=-1">{{ total||msgNum }}</view>

				<text class="text" v-if="!item.fabu" :style="activeIndex == index && activeColor ? 'color:'+ activeColor +';': ''">{{ item.name }}</text>
			</view>
		</view>
		<show-model @models="model=false" :model="model" :content="conArr" :getConfirmFn="modelConfirm" :getCancelFn="modelCancel"></show-model>
	</view>
</template>

<script>
	var _this;
	var timerBottom;
	// components/bottom_nav/bottom_nav.js
	const app = getApp();
	import showModel from '../../components/showModel/showModel';
	import refreshToken from '../../utils/refreshToken.js'
	export default {
		emits:['totop'], //新增  diy首页增加 点击当前底部导航按钮 返回顶部
		components: {
			showModel,
		},
		data() {
			return {
				// showModel组件数据--------
				model: false, //模型弹窗
				conArr: [{
					text: '检测到你目前的城市为',
					style: ''
				}, {
					text: '苏州',
					style: `font-size:50rpx;color:#ff6600;font-weight:bold;padding:10rpx 0rpx`,
				}, {
					text: '是否切换',
					style: ''
				}],
				modelConfirm: function() {
					console.log('确定');
				},
				modelCancel: function() {
					uni.setStorage({ // 不再出现提示
						key: 'manualChange',
						data: 1
					});
				},
				// -------showModel组件数据
				bottomNavArr: [],

				//导航
				msgNum: 0, //未读消息,
				userid: app.globalData.userid,

				grayscale: app.globalData.appConfig.sitePageGray == '1' || app.globalData.appConfig.sitePageGray == '2' ?
					'grayscale' : '',
				// 兼容项
				platForm: app.globalData.platForm,
				timerBottom:null,//加载消息
				activeIndex:0, //可能需要动态修改
			};
		},
		/**
		 * 组件的属性列表
		 */
		props: {
			module: {
				//模块
				type: String,
				default: 'info'
			},
			active: { //必传
				//当前
				type: String,
				default: '0'
			},
			needMessage: { //可选
				type: Boolean,
				default: false
			},
			total: { //可选(若total=-1,则表示不用该组件默认接口的统计数据)
				type: Number,
				default: 0,
			},
			pageHide: { //needMessage为true时，必传
				type: Boolean,
				default: false
			},
			needCity: { //是否需要切换城市提醒弹窗，默认需要
				type: Boolean,
				default: true
			},
			activeColor:{ //选择颜色，默认不设置
				type:String,
				default:'',
			}
		},
		/**
		 * 组件的方法列表
		 */
		methods: {
			linkTo(url, navi) {
				if (url) {
					if (_this.appBoolean) {
						window.setupWebViewJavascriptBridge(function(bridge) {
							bridge.callHandler('redirectNative', {
								'name': '',
								'code': '',
								'link': url
							}, function() {});
						})
						return false
					}
					if (_this.platForm == 'web') { //H5
						if (url.indexOf('http') > -1) {
							location.href = url;
						} else {
							uni.redirectTo({
								url: url
							});
						}
					} else { //小程序
						if (url.includes('/packages') && !url.includes('/index/index')) {
							uni.navigateTo({
								url: url
							})
						} else {
							if (navi) {
								uni.navigateTo({
									url: url.indexOf('http') > -1 ? '/pages/redirect/index?url=' +
										encodeURIComponent(
											url) : url
								})
							} else {
								uni.redirectTo({
									url: url.indexOf('http') > -1 ? '/pages/redirect/index?url=' +
										encodeURIComponent(
											url) : url
								})
							}
						}
					}
				}
			},
			handlePageShow: function() {
				// 在组件实例进入页面节点树时执行
				var userid = app.globalData.userid;
				_this.grayscale = app.globalData.appConfig.sitePageGray == '1' || app.globalData.appConfig
					.sitePageGray == '2' ? 'grayscale' : ''
				var mod = _this.module;
				_this.getModule(mod);
				//获取未读消息
				if (userid != null && userid != 'undefined' && userid) {
					if(_this.module == 'zhaopin'){

						_this.getZhaopinMsg();
						if (_this.needMessage) {
							if(_this.timerBottom){
								clearInterval(_this.timerBottom)
							}
							_this.timerBottom = setInterval(function() {
								_this.getZhaopinMsg()
							}, 5000)
							_this.pageShowCheck(5)
						}
					}else{

						_this.getMessage();
						if (_this.needMessage) {
							_this.timerBottom = setInterval(function() {
								_this.getMessage()
								// console.log('默认')
							}, 5000)
							_this.pageShowCheck(5)
						}
					}
				}
			},

			// 获取模块底部按钮
			getModule(mod) {
				var dataPrarm = 'service=siteConfig&action=touchHomePageFooter&version=2.0&module=' + mod;
				var urlData = app.encodeUrl(dataPrarm);
				_this.$ajax.post({
					url: 'include/ajax.php?' + (urlData ? urlData : dataPrarm),
				}).then(res => {
					var data = res.data;
					if (data.state == 100) {
						var info = data.info;
						var list = [];
						for (var i = 0; i < info.length; i++) {
							//如果未登录，在URL后边带上指定参数，通过服务端强退web-view页面的登录状态
							info[i].url = app.addUrlParam(info[i].url, 'forcelogout');
							// if (info[i].miniPath && info[i].miniPath.indexOf('/packages/') > -
							// 	1) { //分包路径做特殊处理
							// 	let newArr = info[i].miniPath.split('/');
							// 	info[i].miniPath += '/' + newArr[newArr.length - 1]
							// }
							list.push(info[i]);
						}
						_this.bottomNavArr = list
						if(_this.activeIndex >= list.length){
							// 表示没有被选中 此时activeIndex表示最后一个
							_this.activeIndex = list.length - 1
						}
					}
				})
			},

			// 获取模块底部按钮
			getMessage() {
				// console.log('底部信息获取')
				if(!app.globalData.userid){ // 此处判断是为避免 userid被清空后 还是在请求消息统计
					clearInterval(_this.timerBottom)
				}
				var dataPrarm = 'service=member&action=message&type=tongji&im=1';
				var urlData = app.encodeUrl(dataPrarm);
				_this.$ajax.post({
					url: 'include/ajax.php?' + urlData,
				}).then(res => {
					var data = res.data;
					if (data.state == 100) {
						_this.msgNum = data.info.pageInfo.total > 99 ? '99+' : data.info.pageInfo
							.total
					} else if (data.info == '用户信息验证失败') {
						_this.msgNum = 0
						//如果1秒后还没有登录信息，则自动退出并打开登录页面
						setTimeout(function() {
							//如果access_token不存在，直接清空storeage数据并跳转到登录页面
							if (!uni.getStorageSync('access_token')) {
								//退出
								uni.showToast({
									title: '账号状态异常，请重新登录！',
									icon: 'none',
									duration: 2000
								});
								uni.removeStorage({
									key: 'userid'
								});
								uni.removeStorage({
									key: 'access_token'
								});
								uni.removeStorage({
									key: 'refresh_token'
								});
								uni.removeStorage({
									key: 'token_expired'
								});
								app.globalData.userid = null;
								app.globalData.access_token = null;
								app.globalData.refresh_token = null;
								app.globalData.token_expired = null;
								app.tologin('/pages/goback');

								//如果access_token存在，并且接口还提示『用户信息验证失败』，可能是账号在多个设备上进行了登录，此时需要用refresh_token验证下状态，如果可用，则更新本地token，如果不可用，则清空storeage数据并回到首页
							} else {
								var res =  refreshToken.unit(uni.getStorageSync('refresh_token'),
									app.globalData.masterDomain,
									function(datas) {
										if (datas.state == 100) {
											console.log('更新成功');
											// console.log(datas.info);
											var access_token = datas.info.access_token;
											var refresh_token = datas.info.refresh_token;

											// console.log('更新token：' + new Date());
											// console.log(datas.info);

											uni.setStorage({
												key: 'access_token',
												data: access_token
											});
											uni.setStorage({
												key: 'refresh_token',
												data: refresh_token
											});
											var token_expired = Date.parse(new Date()) / 1000 +
												7200 - 20; //两个小时有效期，保险起见，用1小时59分钟40秒
											uni.setStorage({
												key: 'token_expired',
												data: token_expired
											});
											app.globalData.access_token = access_token;
											app.globalData.refresh_token = refresh_token;
											app.globalData.token_expired = token_expired;
										} else {
											//清除缓存数据
											uni.removeStorage({
												key: 'userid'
											});
											uni.removeStorage({
												key: 'access_token'
											});
											uni.removeStorage({
												key: 'refresh_token'
											});
											uni.removeStorage({
												key: 'token_expired'
											});
											app.globalData.userid = null;
											app.globalData.access_token = null;
											app.globalData.refresh_token = null;
											app.globalData.token_expired = null;

											//跳转到登录页面
											// var isLoginning = wx.getStorage('isLoginning');
											// if(!isLoginning){
											//     wx.setStorage({
											//         key:"isLoginning",
											//         data:1
											//     })

											var url = encodeURIComponent(app.globalData
												.masterDomain + '/logout.html?redirect=' +
												app.globalData.masterDomain + '/login.html'
											);
											uni.redirectTo({
												url: '/pages/redirect/index?url=' +
													encodeURIComponent(url),
												success: res => {
													console.log('跳转');
												}
											});
											// }
										}
									});

							}
						}, 1000);
					}
				})
			},

			// 跳转路径 => 页面重定向
			goLink(e, navi) {
				var url = e.currentTarget.dataset.url;
				var type = e.currentTarget.dataset.type;
				var mod = e.currentTarget.dataset.module;
				if (url == '') {
					if(_this.module == 'siteConfig' && _this.active == '0'){
						_this.$emit('totop');
					}
					return false;
				}
				if(_this.platForm == 'mp-weixin' || _this.platForm == 'mp-toutiao'){
					if(url.indexOf('/message/') <= -1 && url.indexOf('/pages/member/index/index/') <= -1 && mod == 'siteConfig'){
						navi = true
					}else{
						navi = false
					}
				}
				if (type == '2' || url.indexOf('/message/') > -1 || url.indexOf('fabuJoin_touch_popup') > -1) {
					let userid = app.globalData.userid;
					if (userid) {
						if (userid == null || userid == '') {
							//未登录或者登录异常
							app.loginCheck(url);
						} else {
							_this.linkTo(url, navi)
						}
					} else {
						app.loginCheck(url);
					}
				} else {
					_this.linkTo(url, navi)
				}
			},
			cityChange() {
				if (this.module == 'waimai' || !this.needCity) { //不需要切换提醒的模块
					return false
				}
				let result;
				result = uni.getStorageSync('cityInfo');
				result = result && typeof(result) == 'string' ? JSON.parse(result) : result;
				app.globalData.locationFn({ //定位
					type: 'gcj02',
					success: res => {
						app.getCityInfo(res.longitude || res.lng, res.latitude || res.lat, 'gcj02ll', function(
							cityPosi) {
							var dataPrarm =
								`service=siteConfig&action=verifyCity&region=${cityPosi.province}&city=${cityPosi.city}&town=${cityPosi.town}&district=${cityPosi.district}`;
							var urlData = app.encodeUrl(dataPrarm);
							_this.$ajax.post({
								url: 'include/ajax.php?' + urlData,
							}).then(res => {
								if (res.data.state == 100) {
									if (!result) {
										// _this.model = true; //注释原因：未获取到分站信息 直接跳转分站选择  不需要弹出切换分站
										_this.conArr[1].text = "城市信息获取失败，是否切换到";
										console.log('跳转城市选择')

									} else if (result.cityid != res.data.info.cityid) {
										if(app.globalData.appConfig && app.globalData.appConfig.site_city_auto_location){ //新增 动定位功能开关
											_this.model = true;

										}
									}
									_this.conArr[1].text = res.data.info.name;
									_this.modelConfirm = function() { //确定按钮的事件
										uni.setStorageSync('cityInfo', res.data.info);
										_this.model = false;
										console.log('重新加载')
										let platform = uni.getSystemInfoSync().uniPlatform
										if(platform == 'web'){
											if(window.appBoolean){
												window.setupWebViewJavascriptBridge(function(bridge) {
													bridge.callHandler('changeCity', JSON.stringify(res.data.info), function(){
														location.href = res.data.info.url + '?currentPageOpen=1&appIndex=1&appFullScreen';
													});
												});
											}else{
												let channelDomainClean = window.masterDomains ? window.masterDomains.replace("http://", "").replace("https://", "") : window.location.host;
												let channelDomain_1 = channelDomainClean.split('.');
												let channelDomain_1_ = channelDomainClean.replace(channelDomain_1[0]+".", "");
												let channelDomain_ = channelDomainClean.split("/")[0];
												channelDomain_1_ = channelDomain_1_.split("/")[0];
												window.$.cookie('HN_siteCityInfo',JSON.stringify(res.data.info), {expires: 7, domain: channelDomainClean, path: '/'})
												window.$.cookie('HN_siteCityInfo',JSON.stringify(res.data.info), {expires: 7, domain: channelDomain_1_, path: '/'})
												location.href = res.data.info.url + '?currentPageOpen=1';
											}
										}else{

											app.reloadFn();
										}
									}
								}
							})
						});
					},
				})
			},

			// 页面切换至前后台之后触发
			pageChangeVisible(val){
				if(val){ //表示显示在前台
					if(this.needMessage && Boolean(app.globalData.userid)){
						clearInterval(this.timerBottom)
						if(this.module == 'zhaopin'){
							this.getZhaopinMsg();
							this.timerBottom = setInterval(res => {
								this.getZhaopinMsg();
								console.log('前台重置')
							}, 5000)
						}else{
							this.getMessage();
							this.timerBottom = setInterval(res => {
								this.getMessage();
								console.log('前台重置')
							}, 5000)
						}
						this.pageShowCheck(5)
					}
				}else{ //表示切换至后台
					clearInterval(this.timerBottom)
				}	
			},
			pageShowCheck(timeOut){ // timeOut => 单位是分钟 一段时间过后 修改定时器  interval请求时间间隔 单位是秒
				// console.log(timeOut)
				const that = this;
				let next_timeOut = timeOut;
				let interval = 5
				switch(timeOut){
					case 5: 
						next_timeOut = 10,
						interval = 10;
						break;
					case 10: 
						next_timeOut = 20,
						interval = 20;
						break;
					case 20: 
						next_timeOut = 30,
						interval = 30;
						break;
					case 30: 
						next_timeOut = 60,
						interval = 60;
						break;
					case 60: 
						next_timeOut = 0,
						interval = 0;
						break;
				}
				setTimeout(() => {
					clearInterval(that.timerBottom)
					if(timeOut && interval){
						if(that.module == 'zhaopin'){
							that.timerBottom = setInterval(this.getZhaopinMsg,interval * 1000)
						}else{
							that.timerBottom = setInterval(this.getMessage,interval * 1000)
						}
					}
					if(next_timeOut){
						that.pageShowCheck(next_timeOut)
					}
				},timeOut * 60 * 1000);
			},

			async getZhaopinMsg(){
				const that = this;
				let zhaopinData = uni.getStorageSync('zhaopinData') || {}
				let user_type = zhaopinData.user_type || 0
				let type = user_type == 2 ? 1 : 0
				let url = `include/ajax.php?service=zhaopin&action=getUnreadTotal&userid=${app.globalData.userid}&type=${type}`
				let result = await that.$ajax.post({
					url: app.encodeUrl(url),
				});
				if (result.data.state == 100) {
					that.msgNum = result.data.info == -1 ? 0 : result.data.info;
				}
			},
		},
		mounted() {
			_this = this;
			// 处理小程序 attached 生命周期
			this.handlePageShow();
			// 手动切换城市不提示，仅生效一次
			let pop_cityid = uni.getExtConfigSync && uni.getExtConfigSync()['cityid'] ?
			uni.getExtConfigSync()['cityid'] : '';    //此处为了兼容但分站打包
			if(!pop_cityid){
				uni.getStorage({
					key: 'manualChange',
					fail: res => {
						setTimeout(() => {
							_this.cityChange();
						}, 1500);
					}
				})
			}
			_this.activeIndex = _this.active
			// app.watch(this.pageChangeVisible,'pageVisible')  undefined报错
		},
		unmounted() {
			// 在组件实例被从页面节点树移除时执行 
			clearInterval(_this.timerBottom);
		},
		watch: {
			pageHide(newVal, oldVal) {

				if (newVal) {
					clearInterval(_this.timerBottom);
				} else if (Boolean(app.globalData.userid)) {
					clearInterval(_this.timerBottom )
					_this.timerBottom = setInterval(res => {
						if(this.module == 'zhaopin'){
							this.getZhaopinMsg()
						}else{

							this.getMessage();
						}
						// console.log('pageHide')
					}, 5000)
				}
			},
			total(newVal, oldVal) { //这个参数是可选的，如果其他页面给他设置成0，msgNum也要变成0，清掉未读数据。如果不传，则没有影响
				if (newVal == 0) {
					this.msgNum = 0;
				}
			}
		}
	};
</script>
<style>
	@import './bottom_nav.css';
</style>